﻿@{
    ViewData["Title"] = "库存盘点管理";
}

<!-- 添加隐藏字段存储当前用户 -->
@Html.Hidden("CurrentUser", User.Identity?.Name ?? "admin")

<div id="app" class="container">
    <!-- 加载提示 -->
    <el-loading v-if="loading" fullscreen text="加载中..."></el-loading>

    <!-- 搜索区域 -->
    <div class="search-bar">
        <el-form inline :model="searchForm">
            <el-form-item label="盘点单号">
                <el-input v-model="searchForm.orderNo" placeholder="请输入" style="width: 200px;"></el-input>
            </el-form-item>
            <el-form-item label="盘点结果">
                <el-select v-model="searchForm.result" placeholder="请选择" style="width: 150px;">
                    <el-option label="全部" value=""></el-option>
                    <el-option label="草稿" value="0"></el-option>
                    <el-option label="待审核" value="1"></el-option>
                    <el-option label="有盈亏" value="2"></el-option>
                    <el-option label="无盈亏" value="3"></el-option>
                    <el-option label="已作废" value="4"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="盘点类型">
                <el-select v-model="searchForm.type" placeholder="请选择" style="width: 150px;">
                    <el-option label="全部" value=""></el-option>
                    <el-option label="存货盘点" value="存货盘点"></el-option>
                    <el-option label="定期盘点" value="定期盘点"></el-option>
                    <el-option label="临时盘点" value="临时盘点"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="仓库名称">
                <el-select v-model="searchForm.warehouse"
                           placeholder="请选择"
                           style="width: 180px;"
                           :loading="warehouseLoading"
                           :disabled="warehouseLoading">
                    <el-option label="全部" value=""></el-option>
                    <el-option v-for="warehouse in warehouseList"
                               :key="warehouse.warehouse_id"
                               :label="warehouse.warehouse_name"
                               :value="warehouse.warehouse_name">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="default" @@click="resetForm">重置</el-button>
                <el-button type="primary" @@click="searchData">查询</el-button>
            </el-form-item>
        </el-form>
    </div>

    <!-- 操作按钮区域 -->
    <div class="btn-group">
        <el-button type="primary" @@click="toAdd">新增</el-button>
        <el-button type="danger" :disabled="selectedRows.length === 0" @@click="batchDelete">批量删除</el-button>
        <el-button type="success" @@click="exportData">导出</el-button>
        <el-button type="warning" :disabled="selectedRows.length === 0" @@click="batchCancel">批量作废</el-button>
        <el-button type="default" @@click="lockWarehouse">锁定仓库</el-button>
        <el-button type="default" @@click="refreshList">刷新</el-button>
    </div>

    <!-- 表格区域 -->
    <div class="table-container">
        <el-table :data="tableData"
                  border
                  @@selection-change="handleSelectionChange"
                  style="width: 100%;"
                  :header-cell-style="{ 'background-color': '#f5f7fa' }">
            <!-- 左固定列 -->
            <el-table-column type="selection" width="55" fixed="left"></el-table-column>
            <el-table-column type="index" label="序号" width="60" fixed="left"></el-table-column>
            <!-- 盘点单号列添加点击事件 -->
            <el-table-column label="盘点单号" width="140" fixed="left">
                <template slot-scope="scope">
                    <span class="clickable-order-no"
                          @@click="toDetail(scope.row.inventory_list_id)"
                          title="点击查看详情">
                        {{ scope.row.inventory_order_no || '-' }}
                    </span>
                </template>
            </el-table-column>
            <el-table-column prop="review_status" label="盘点结果" width="110" fixed="left">
                <template slot-scope="scope">
                    <span :class="getStatusClass(scope.row.review_status)">
                        {{ getStatusText(scope.row.review_status) || '-' }}
                    </span>
                </template>
            </el-table-column>

            <!-- 中间列 -->
            <el-table-column prop="warehouse_name" label="仓库名称" width="130">
                <template slot-scope="scope">{{ scope.row.warehouse_name || '-' }}</template>
            </el-table-column>
            <el-table-column prop="inventory_types" label="盘点类型" width="130">
                <template slot-scope="scope">
                    <span v-if="scope.row.inventory_types">{{ scope.row.inventory_types }}</span>
                    <span v-else>
                        <span style="color: #909399;">-</span>
                        <span v-if="debugMode" style="color: #f56c6c; font-size: 12px;">(未设置)</span>
                    </span>
                </template>
            </el-table-column>
            <el-table-column prop="inventory_start_time" label="盘点开始时间" width="170">
                <template slot-scope="scope">{{ formatDate(scope.row.inventory_start_time) || '-' }}</template>
            </el-table-column>
            <el-table-column prop="stkt_end_time" label="盘点结束时间" width="170">
                <template slot-scope="scope">{{ formatDate(scope.row.stkt_end_time) || '-' }}</template>
            </el-table-column>
            <el-table-column prop="outbound_status" label="出库状态" width="110">
                <template slot-scope="scope">{{ getOutboundStatusText(scope.row.outbound_status) || '-' }}</template>
            </el-table-column>
            <el-table-column prop="storage_status" label="入库状态" width="110">
                <template slot-scope="scope">{{ getStorageStatusText(scope.row.storage_status) || '-' }}</template>
            </el-table-column>
            <!-- 盘点单列表页面的表格列 -->
            <el-table-column prop="product_names" label="盘点货品" width="200">
                <template slot-scope="scope">
                    <span v-if="scope.row.product_names && scope.row.product_names.length > 0">
                        {{ scope.row.product_names | truncate(18) }}
                    </span>
                    <span v-else>
                        <span style="color: #909399;">-</span>
                        <span v-if="debugMode" style="color: #f56c6c; font-size: 12px;">(无明细)</span>
                    </span>
                </template>
            </el-table-column>
            <el-table-column prop="total_quantity" label="盘点数量" width="110" align="right">
                <template slot-scope="scope">{{ scope.row.total_quantity || 0 }}</template>
            </el-table-column>
            <el-table-column prop="total_profit_num" label="盘盈数量" width="110" align="right">
                <template slot-scope="scope">
                    <span style="color: #67c23a;" v-if="scope.row.total_profit_num > 0">+{{ scope.row.total_profit_num }}</span>
                    <span v-else>0</span>
                </template>
            </el-table-column>
            <el-table-column prop="total_loss_num" label="盘亏数量" width="110" align="right">
                <template slot-scope="scope">
                    <span style="color: #f56c6c;" v-if="scope.row.total_loss_num > 0">-{{ scope.row.total_loss_num }}</span>
                    <span v-else>0</span>
                </template>
            </el-table-column>
            <el-table-column prop="total_profit_amount" label="盘盈金额" width="120" align="right">
                <template slot-scope="scope">
                    <span style="color: #67c23a;" v-if="scope.row.total_profit_amount > 0">+{{ scope.row.total_profit_amount.toFixed(2) }}</span>
                    <span v-else>0.00</span>
                </template>
            </el-table-column>
            <el-table-column prop="total_loss_amount" label="盘亏金额" width="120" align="right">
                <template slot-scope="scope">
                    <span style="color: #f56c6c;" v-if="scope.row.total_loss_amount > 0">-{{ scope.row.total_loss_amount.toFixed(2) }}</span>
                    <span v-else>0.00</span>
                </template>
            </el-table-column>
            <el-table-column prop="handler_name" label="经办人" width="110">
                <template slot-scope="scope">{{ scope.row.handler_name || '-' }}</template>
            </el-table-column>
            <el-table-column prop="create_by" label="制单人" width="110">
                <template slot-scope="scope">{{ scope.row.create_by || '-' }}</template>
            </el-table-column>
            <el-table-column prop="department_name" label="所在部门" width="130">
                <template slot-scope="scope">
                    <span v-if="scope.row.department_name">{{ scope.row.department_name }}</span>
                    <span v-else>
                        <span style="color: #909399;">-</span>
                        <span v-if="debugMode" style="color: #f56c6c; font-size: 12px;">(未关联部门)</span>
                    </span>
                </template>
            </el-table-column>
            <el-table-column prop="create_time" label="制单时间" width="170">
                <template slot-scope="scope">{{ formatDate(scope.row.create_time) || '-' }}</template>
            </el-table-column>

            <!-- 右固定列：操作 -->
            <el-table-column label="操作" width="240" fixed="right">
                <template slot-scope="scope">
                   @*  <el-button type="text" size="small" @@click="toEdit(scope.row.inventory_list_id)">编辑</el-button> *@
                    <el-button type="text" size="small" style="color: #f56c6c;" @@click="deleteOne(scope.row.inventory_list_id)">删除</el-button>

                    <!-- 作废按钮（仅草稿和待审核状态显示） -->
                    <el-button type="text" size="small" style="color: #e6a23c;"
                               v-if="scope.row.review_status === 0 || scope.row.review_status === 1"
                               @@click="cancelOne(scope.row.inventory_list_id)">作废</el-button>

                    <!-- 审核按钮（仅待审核状态显示） -->
                    <el-button type="text" size="small" style="color: #409eff;"
                               v-if="scope.row.review_status === 1"
                               @@click="approveOne(scope.row.inventory_list_id)">审核</el-button>
                </template>
            </el-table-column>
        </el-table>
    </div>

    <!-- 分页区域 -->
    <el-pagination @@size-change="handleSizeChange"
                   @@current-change="handleCurrentChange"
                   :current-page="pagination.pageNum"
                   :page-sizes="[10, 20, 50]"
                   :page-size="pagination.pageSize"
                   layout="total, sizes, prev, pager, next, jumper"
                   :total="pagination.total"
                   style="margin-top: 15px; text-align: right;">
    </el-pagination>
</div>

<!-- 引入依赖 -->
<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/element-ui@2.15.13/lib/index.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/element-ui@2.15.13/lib/theme-chalk/index.css">

<script>
    Vue.filter('truncate', function(value, length) {
        if (!value) return '';
        if (value.length <= length) return value;
        return value.slice(0, length) + '...';
    });

    new Vue({
        el: '#app',
        data: {
            searchForm: {
                orderNo: '',
                result: '',
                type: '',
                warehouse: ''
            },
            tableData: [],
            selectedRows: [],
            warehouseList: [],
            warehouseLoading: false,
            pagination: {
                pageNum: 1,
                pageSize: 10,
                total: 0
            },
            loading: false,
            debugMode: true,
            currentUser: 'admin' // 默认用户
        },
        mounted() {
            console.log('页面初始化，加载盘点单数据...');
            this.getCurrentUser(); // 获取当前用户
            this.loadWarehouseList();
            this.searchData();
        },
        methods: {
            // 获取当前登录用户
            getCurrentUser() {
                try {
                    // 从隐藏字段获取当前用户
                    const hiddenUser = $('#CurrentUser').val();
                    if (hiddenUser && hiddenUser !== '') {
                        this.currentUser = hiddenUser;
                        console.log('获取到当前用户:', this.currentUser);
                    } else {
                        // 如果隐藏字段没有值，尝试从后端API获取
                        this.getCurrentUserFromAPI();
                    }
                } catch (error) {
                    console.warn('获取用户信息失败，使用默认用户:', error);
                    this.currentUser = 'admin';
                }
            },

            // 从后端API获取当前用户
            getCurrentUserFromAPI() {
                const _this = this;
                $.get('/InventoryCheck/GetCurrentUser', function(res) {
                    if (res.success && res.data) {
                        _this.currentUser = res.data;
                        console.log('从API获取到当前用户:', _this.currentUser);
                    } else {
                        console.warn('API获取用户失败，使用默认用户');
                        _this.currentUser = 'admin';
                    }
                }).fail(function() {
                    console.warn('获取用户API调用失败，使用默认用户');
                    _this.currentUser = 'admin';
                });
            },

            // 加载仓库列表
            loadWarehouseList() {
                const _this = this;
                _this.warehouseLoading = true;

                $.get('/InventoryCheck/GetAllWarehouses', function(res) {
                    _this.warehouseLoading = false;
                    if (res.success) {
                        _this.warehouseList = res.data || [];
                        console.log(`成功加载 ${_this.warehouseList.length} 个仓库`);
                    } else {
                        _this.$message.error(res.message || '获取仓库列表失败');
                        _this.warehouseList = [];
                    }
                }, 'json').fail(function() {
                    _this.warehouseLoading = false;
                    _this.$message.error('网络错误，无法加载仓库列表');
                    _this.warehouseList = [];
                });
            },

            // 刷新列表
            refreshList() {
                console.log('刷新列表');
                this.loadWarehouseList();
                this.searchData();
            },

            // 查询数据
            searchData() {
                const _this = this;
                _this.loading = true;

                const params = {
                    OrderNo: _this.searchForm.orderNo,
                    ReviewStatus: _this.searchForm.result || null,
                    WarehouseName: _this.searchForm.warehouse,
                    CheckType: _this.searchForm.type,
                    PageIndex: _this.pagination.pageNum,
                    PageSize: _this.pagination.pageSize
                };

                $.post('/InventoryCheck/GetInventoryList', params, function(res) {
                    _this.loading = false;
                    if (res.success) {
                        _this.tableData = res.data || [];
                        _this.pagination.total = res.total || 0;
                    } else {
                        _this.$message.error(res.message || '获取数据失败');
                    }
                }, 'json').fail(function() {
                    _this.loading = false;
                    _this.$message.error('网络错误，无法加载数据');
                });
            },

            // 重置搜索
            resetForm() {
                this.searchForm = {
                    orderNo: '',
                    result: '',
                    type: '',
                    warehouse: ''
                };
                this.pagination.pageNum = 1;
                this.searchData();
            },

            // 单条删除
            deleteOne(id) {
                const _this = this;
                this.$confirm('确定删除该盘点单？删除后不可恢复！', '警告', {
                    type: 'danger'
                }).then(() => {
                    $.post('/InventoryCheck/DeleteInventory', { id }, function(res) {
                        if (res.success) {
                            _this.$message.success('删除成功');
                            _this.searchData();
                        } else {
                            _this.$message.error(res.message || '删除失败');
                        }
                    }).fail(() => _this.$message.error('网络错误'));
                });
            },

            // 批量删除
            batchDelete() {
                const ids = this.selectedRows.map(r => r.inventory_list_id);
                if (ids.length === 0) return;

                const _this = this;
                this.$confirm(`确定删除选中的${ids.length}条盘点单？删除后不可恢复！`, '警告', {
                    type: 'danger'
                }).then(() => {
                    $.post('/InventoryCheck/BatchDeleteInventory', { listIds: ids }, function(res) {
                        if (res.success) {
                            _this.$message.success('批量删除成功');
                            _this.selectedRows = [];
                            _this.searchData();
                        } else {
                            _this.$message.error(res.message || '批量删除失败');
                        }
                    }).fail(() => _this.$message.error('网络错误'));
                });
            },

            // 单条作废
            cancelOne(id) {
                const _this = this;
                this.$confirm('确定作废该盘点单？', '确认', {
                    type: 'warning'
                }).then(() => {
                    $.post('/InventoryCheck/CancelInventory', { id }, function(res) {
                        if (res.success) {
                            _this.$message.success('作废成功');
                            _this.searchData();
                        } else {
                            _this.$message.error(res.message || '作废失败');
                        }
                    }).fail(() => _this.$message.error('网络错误'));
                });
            },

            // 批量作废
            batchCancel() {
                const ids = this.selectedRows.map(r => r.inventory_list_id);
                if (ids.length === 0) return;

                const _this = this;
                this.$confirm(`确定作废选中的${ids.length}条盘点单？`, '确认', {
                    type: 'warning'
                }).then(() => {
                    $.post('/InventoryCheck/BatchCancelInventory', { listIds: ids }, function(res) {
                        if (res.success) {
                            _this.$message.success('批量作废成功');
                            _this.selectedRows = [];
                            _this.searchData();
                        } else {
                            _this.$message.error(res.message || '批量作废失败');
                        }
                    }).fail(() => _this.$message.error('网络错误'));
                });
            },

            // 单条审核
                approveOne(id) {
        const _this = this;
        this.$confirm('确定审核该盘点单？审核后将更新库存状态', '确认', {
            type: 'primary'
        }).then(() => {
            // 使用获取到的当前用户作为审核人
            const reviewer = _this.currentUser;
            console.log('审核操作，审核人:', reviewer, '盘点单ID:', id);

            $.post('/InventoryCheck/ApproveInventory', { id, reviewer }, function(res) {
                if (res.success) {
                    // 审核成功后，检查是否有盈亏
                    if (res.data && res.data.isNoProfitLoss) {
                        _this.$message.success('审核成功，状态更新为：无盈亏');
                    } else {
                        _this.$message.success('审核成功，状态更新为：有盈亏');
                    }
                    _this.searchData(); // 重新加载数据以显示最新状态
                } else {
                    _this.$message.error(res.message || '审核失败');
                }
            }).fail(() => _this.$message.error('网络错误'));
        });
    },

            // 锁定仓库
            lockWarehouse() {
                window.location.href = '/Warehouse/Index';
            },

            // 导出数据
            exportData() {
                const params = {
                    OrderNo: this.searchForm.orderNo,
                    ReviewStatus: this.searchForm.result || null,
                    WarehouseName: this.searchForm.warehouse,
                    CheckType: this.searchForm.type
                };

                let url = '/InventoryCheck/ExportInventoryList?';
                Object.keys(params).forEach(key => {
                    if (params[key]) url += `${key}=${encodeURIComponent(params[key])}&`;
                });

                window.open(url, '_blank');
            },

            // 分页相关
            handleSizeChange(size) {
                this.pagination.pageSize = size;
                this.pagination.pageNum = 1;
                this.searchData();
            },
            handleCurrentChange(page) {
                this.pagination.pageNum = page;
                this.searchData();
            },
            handleSelectionChange(val) {
                this.selectedRows = val;
            },

            // 状态文本转换
            getStatusText(status) {
                const map = { 0: '草稿', 1: '待审核', 2: '有盈亏', 3: '无盈亏', 4: '已作废' };
                return map[status] || status;
            },
            getOutboundStatusText(status) {
                const map = { 0: '未出库', 1: '部分出库', 2: '已出库', 3: '无需出库' };
                return map[status] || status;
            },
            getStorageStatusText(status) {
                const map = { 0: '未入库', 1: '部分入库', 2: '已入库', 3: '无需入库' };
                return map[status] || status;
            },
            getStatusClass(status) {
                const map = {
                    0: 'status-draft',
                    1: 'status-pending',
                    2: 'status-profit',
                    3: 'status-noprofit',
                    4: 'status-canceled'
                };
                return map[status] || '';
            },

            // 日期格式化
            formatDate(dateStr) {
                if (!dateStr) return '';
                try {
                    const date = new Date(dateStr);
                    return date.toLocaleString('zh-CN', {
                        year: 'numeric',
                        month: '2-digit',
                        day: '2-digit',
                        hour: '2-digit',
                        minute: '2-digit',
                        second: '2-digit'
                    }).replace(/\//g, '-');
                } catch (e) {
                    return dateStr;
                }
            },

            // 跳转页面
            toAdd() {
                window.location.href = '/InventoryCheck/Add';
            },
            toEdit(id) {
                window.location.href = `/InventoryCheck/Add?id=${id}`;
            },
            toDetail(id) {
                console.log(`点击盘点单号，跳转到详情页，ID: ${id}`);
                window.location.href = `/InventoryCheck/Detail?id=${id}`;
            }
        }
    });
</script>

<style>
    .container {
        padding: 20px;
    }

    .search-bar {
        margin-bottom: 15px;
        padding: 15px;
        background: #f5f7fa;
        border-radius: 4px;
    }

    .btn-group {
        margin-bottom: 15px;
    }

    .table-container {
        width: 100%;
        overflow-x: auto;
        margin-bottom: 20px;
    }

    .el-table__fixed-left, .el-table__fixed-right {
        height: auto !important;
        bottom: 0 !important;
        box-shadow: 2px 0 6px rgba(0, 0, 0, 0.08);
    }

    .status-draft {


        color: #606266;
    }

    .status-pending {
        color: #e6a23c;
        color: #e6a23c;
    }

    .status-profit {
        color: #67c23a;
    }

    .status-noprofit {
        color: #909399;
    }

    .status-canceled {
        color: #f56c6c;
    }

    .clickable-order-no {
        color: #409eff;
        cursor: pointer;
        text-decoration: underline;
        transition: color 0.2s;
    }

        .clickable-order-no:hover {
            color: #66b1ff;
        }
</style>